package com.bw.dg.aop;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.binding.MapperMethod;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;


/**
 * @ProjectName: guding
 * @Package: com.bw.dg.aop
 * @ClassName: MethodLogAspect
 * @Author: 社会佩奇
 * @Description: MethodLogAspect
 * @Date: 2020/4/22 18:46
 * @Version: 1.0
 */

//证明是一个配置文件(使用@Component也可以,因为点入后会发现@Configuration还是使用了@Component)
@Configuration
//证明是一个切面
@Aspect
public class MethodLogAspect {

    @Pointcut("@annotation(com.bw.dg.common.MethodLog)")
    public void log() {
    }

    /**
     * 加入注解自动记录方法日志
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around(value = "log()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取执行方法的类的名称（包名加类名）
        String className = joinPoint.getTarget().getClass().getName();
        // 获取实例和方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Logger log = LoggerFactory.getLogger(className);
        Object[] args = joinPoint.getArgs();
        // 记录日志
        log.info(className + "#" + method.getName() + " start..., params:{}", JSON.toJSONString(args));
        long startTime = System.currentTimeMillis();
        // 执行方法获取返回值
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        // 记录日志
        log.info(className + "#" + method.getName() + " end, execute time: [{}],  return: {}", end - startTime, JSON.toJSONString(proceed));
        // 返回
        return proceed;
    }


}
